package com.huanxing.cloud.user.controller.app;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huanxing.cloud.common.core.constant.CacheConstants;
import com.huanxing.cloud.common.core.constant.MallCommonConstants;
import com.huanxing.cloud.common.core.util.Result;
import com.huanxing.cloud.common.security.annotation.HxInner;
import com.huanxing.cloud.common.security.util.SecurityUtils;
import com.huanxing.cloud.user.api.dto.UserInfoDTO;
import com.huanxing.cloud.user.api.entity.UserInfo;
import com.huanxing.cloud.user.api.vo.UserInfoVO;
import com.huanxing.cloud.user.api.vo.UserRespVO;
import com.huanxing.cloud.user.service.IUserInfoService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

/**
 * 商城用户
 *
 * @author lijx
 * @since 2022/3/1 10:13
 */
@Slf4j
@AllArgsConstructor
@RestController
@RequestMapping("/app/userinfo")
@Tag(description = "userinfo", name = "商城用户-API")
public class AppUserInfoController {

	private final IUserInfoService userInfoService;

	private final RedisTemplate<String, String> redisTemplate;

	@Operation(summary = "注册用户")
	@PostMapping("/register")
	public Result register(HttpServletRequest request, @RequestBody UserInfo userInfo) {
		if (userInfoService.checkPhone(userInfo.getPhone())) {
			return Result.fail("手机号已存在");
		}
		userInfo.setUserSource(request.getHeader(MallCommonConstants.HEADER_CLIENT_TYPE));
		return Result.success(userInfoService.save(userInfo));
	}

	@Operation(summary = "获取用户信息")
	@GetMapping
	public Result<UserRespVO> getUserInfo() {
		return Result.success(userInfoService.getUserById(SecurityUtils.getUser().getUserId()));
	}

	@Operation(summary = "修改用户信息")
	@PostMapping("/update/info")
	public Result updateInfo(@RequestBody UserInfo userInfo) {
		userInfo.setPhone(null);
		userInfo.setPassword(null);
		userInfo.setUserSource(null);
		userInfo.setUserGrade(null);
		userInfo.setUserNumber(null);
		userInfo.setAccountBalance(null);
		userInfo.setParentId(null);
		return Result.success(userInfoService.updateById(userInfo));
	}

	@Operation(summary = "用户修改手机号")
	@PostMapping("/update/phone")
	public Result updatePhone(@RequestBody UserInfoDTO userInfoDTO) {
		String randomStr = userInfoDTO.getPhone();
		String key = CacheConstants.DEFAULT_CODE_KEY + randomStr;
		Object codeObj = redisTemplate.opsForValue().get(key);

		if (ObjectUtil.isEmpty(codeObj) || !userInfoDTO.getCode().equals(codeObj)) {
			return Result.fail("验证码不合法");
		}
		String userId = SecurityUtils.getUser().getUserId();
		// 查询手机号是否已存在
		long count = userInfoService.count(Wrappers.<UserInfo>lambdaQuery()
			.eq(UserInfo::getPhone, userInfoDTO.getPhone())
			.ne(UserInfo::getId, userId));
		if (count > 0) {
			return Result.fail("手机号已存在");
		}
		UserInfo userInfo = new UserInfo();
		userInfo.setId(userId);
		userInfo.setPhone(userInfoDTO.getPhone());
		return Result.success(userInfoService.updateById(userInfo));
	}

	@HxInner
	@GetMapping("/phone/{phone}/{clientType}")
	public Result<UserInfo> getInfoByPhone(@PathVariable("phone") String phone,
			@PathVariable("clientType") String clientType) {
		UserInfo userInfo = userInfoService.getOne(Wrappers.<UserInfo>lambdaQuery().eq(UserInfo::getPhone, phone));
		if (ObjectUtil.isNull(userInfo)) {
			userInfo = userInfoService.createUser(phone, clientType);

		}
		return Result.success(userInfo);
	}

	/**
	 * 商城用户查询
	 * @param userId 用户id
	 * @return UserInfoVO
	 */
	@HxInner
	@GetMapping("/{userId}")
	public Result<UserInfoVO> getById(@PathVariable("userId") String userId) {
		UserInfo userInfo = userInfoService.getById(userId);
		if (Objects.isNull(userInfo)) {
			return Result.fail();
		}
		return Result.success(BeanUtil.copyProperties(userInfo, UserInfoVO.class));
	}

	/**
	 * 商城用户查询
	 * @param phone 手机号
	 * @return UserInfoVO
	 */
	@HxInner
	@GetMapping("/getByPhone/{phone}")
	public Result<UserInfoVO> getByPhone(@PathVariable("phone") String phone) {
		UserInfo userInfo = userInfoService.getOne(Wrappers.<UserInfo>lambdaQuery().eq(UserInfo::getPhone, phone));
		if (Objects.isNull(userInfo)) {
			return Result.fail();
		}
		return Result.success(BeanUtil.copyProperties(userInfo, UserInfoVO.class));
	}

}
